package com.defense;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ClassList {
    JFrame jf = new JFrame("班级列表");
    final int width = 800;
    final int height = 600;
    JTextField inputField = new JTextField(20);

    // 存储从文件中读取的班级名称数据
    private List<String> classNames = new ArrayList<>();

    // 用于存储表格组件
    private JTable table;

    public void init() {
        jf.setBounds((Toolkit.getDefaultToolkit().getScreenSize().width - width) / 2,
                (Toolkit.getDefaultToolkit().getScreenSize().height - height) / 2,
                width, height);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jf.setLayout(new BorderLayout());

        // 创建顶部面板
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());

        // 创建左侧面板，放置输入框
        JPanel leftPanel = new JPanel();
        leftPanel.setPreferredSize(new Dimension(width / 3, 50));
        leftPanel.add(inputField);

        // 创建右侧面板，放置按钮
        JPanel rightPanel = new JPanel();
        rightPanel.setPreferredSize(new Dimension(2 * width / 3, 50));
        rightPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0)); // 使用FlowLayout使按钮水平居中，并设置间距

        // 创建按钮
        JButton queryButton = new JButton("查询");
        JButton setClassButton = new JButton("设置班级");
        JButton exportButton = new JButton("导出成绩");
        JButton backButton = new JButton("返回");
        JButton deleteButton = new JButton("删除");

        // 为查询按钮添加事件监听器
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 读取classes.txt文件中的数据并根据输入框内容筛选
                readAndFilterClassDataFromFile();

                // 在输入框和按钮下方展示数据
                showDataInTable();
            }
        });

        // 为设置班级按钮添加事件监听器
        setClassButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow!= -1) {
                    // 获取选中行班级列的内容
                    String selectedClassName = (String) table.getValueAt(selectedRow, 1);

                    // 将班级名称保存到class.txt文件中
                    saveClassNameToFile(selectedClassName);

                    JOptionPane.showMessageDialog(jf, "设置成功");
                } else {
                    JOptionPane.showMessageDialog(jf, "请先选中要设置班级的行！");
                }
            }
        });

        // 为删除按钮添加事件监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow!= -1) {
                    // 从列表中删除数据
                    String classNameToDelete = classNames.get(selectedRow);
                    classNames.remove(selectedRow);

                    // 从表格模型中删除数据
                    ((DefaultTableModel) table.getModel()).removeRow(selectedRow);

                    // 在classes.txt文件中删除对应数据
                    deleteClassDataFromFile(classNameToDelete);

                    JOptionPane.showMessageDialog(jf, "已成功删除所选班级信息！");
                }
            }
        });

        // 为返回按钮添加事件监听器
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MangerInterface mangerInterface = new MangerInterface();
                mangerInterface.init();
                jf.setVisible(false);
                jf.dispose();
            }
        });

        // 将按钮添加到右侧面板
        rightPanel.add(queryButton);
        rightPanel.add(setClassButton);
        rightPanel.add(exportButton);
        rightPanel.add(backButton);
        rightPanel.add(deleteButton);

        // 将左右面板添加到顶部面板
        topPanel.add(leftPanel, BorderLayout.WEST);
        topPanel.add(rightPanel, BorderLayout.EAST);

        // 将顶部面板添加到主窗口
        jf.add(topPanel, BorderLayout.NORTH);

        // 在输入框和按钮下方添加一个面板用于放置表格
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout());
        jf.add(centerPanel, BorderLayout.CENTER);

        jf.setVisible(true);
    }

    // 从文件中读取班级数据并根据输入框内容筛选，存储到classNames列表中
    private void readAndFilterClassDataFromFile() {
        classNames.clear();
        String inputText = inputField.getText();
        try (BufferedReader br = new BufferedReader(new FileReader("classes.txt"))) {
            String line;
            while ((line = br.readLine())!= null) {
                if (inputText.isEmpty() || line.contains(inputText)) {
                    classNames.add(line);
                }
            }
        } catch (IOException ex) {

        }

        try (FileWriter fw = new FileWriter("classes.txt")) {
            for (String className : classNames) {
                fw.write(className + "\n");
            }
        } catch (IOException ex) {

        }
    }


    private void showDataInTable() {
        // 创建表格数据模型
        Object[][] data = new Object[classNames.size()][2];
        for (int i = 0; i < classNames.size(); i++) {
            data[i][0] = "";
            data[i][1] = classNames.get(i);
        }
        String[] columnNames = {"项目", "班级名称"};
        DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);

        // 创建表格组件
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        // 将表格添加到中心面板
        JPanel centerPanel = (JPanel) jf.getContentPane().getComponent(1);
        centerPanel.add(scrollPane, BorderLayout.CENTER);
        jf.revalidate();
        jf.repaint();
    }

    // 在classes.txt文件中删除指定班级数据
    private void deleteClassDataFromFile(String classNameToDelete) {
        List<String> updatedClassNames = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader("classes.txt"))) {
            String line;
            while ((line = br.readLine())!= null) {
                if (!line.equals(classNameToDelete)) {
                    updatedClassNames.add(line);
                }
            }
        } catch (IOException ex) {

        }

        try (FileWriter fw = new FileWriter("classes.txt")) {
            for (String className : updatedClassNames) {
                fw.write(className + "\n");
            }
        } catch (IOException ex) {

        }
    }

    // 将班级名称保存到class.txt文件
    private void saveClassNameToFile(String className) {
        try (FileWriter fw = new FileWriter("class.txt", true)) {
            fw.write(className + "\n");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main() {
        new ClassList().init();
    }
}